import { _decorator, Component, Node, Vec3 } from 'cc';
import { Player } from '../entity/Player';
import { NetworkManager } from './NetworkManager';

const { ccclass, property } = _decorator;

/**
 * 网络玩家组件
 * 
 * 功能：
 * 1. 处理玩家网络同步
 * 2. 管理玩家状态更新
 * 3. 处理延迟补偿
 * 4. 提供预测和插值
 */
@ccclass('NetworkPlayer')
export class NetworkPlayer extends Component {
    @property(Player)
    private player: Player | null = null;

    private networkId: string = '';
    private lastUpdateTime: number = 0;
    private interpolationDelay: number = 0.1;
    private positionBuffer: { position: Vec3, timestamp: number }[] = [];

    public init(networkId: string): void {
        this.networkId = networkId;
        this.setupNetworkCallbacks();
    }

    private setupNetworkCallbacks(): void {
        NetworkManager.instance.on('playerMove', this.onPlayerMove.bind(this));
        NetworkManager.instance.on('playerAttack', this.onPlayerAttack.bind(this));
        NetworkManager.instance.on('playerEvolve', this.onPlayerEvolve.bind(this));
    }

    private onPlayerMove(data: { id: string, position: Vec3, timestamp: number }): void {
        if (data.id !== this.networkId) return;

        // 添加位置到缓冲区
        this.positionBuffer.push({
            position: new Vec3(data.position.x, data.position.y, data.position.z),
            timestamp: data.timestamp
        });

        // 保持缓冲区大小
        while (this.positionBuffer.length > 10) {
            this.positionBuffer.shift();
        }
    }

    private onPlayerAttack(data: { id: string, target: string }): void {
        if (data.id !== this.networkId) return;
        this.player?.useSkill('attack');
    }

    private onPlayerEvolve(data: { id: string, stage: string }): void {
        if (data.id !== this.networkId) return;
        // 处理进化
    }

    update(dt: number) {
        this.updatePlayerPosition(dt);
    }

    private updatePlayerPosition(dt: number): void {
        if (this.positionBuffer.length < 2) return;

        const now = Date.now() / 1000 - this.interpolationDelay;
        
        // 找到合适的插值点
        while (this.positionBuffer.length >= 2 &&
               this.positionBuffer[1].timestamp <= now) {
            this.positionBuffer.shift();
        }

        if (this.positionBuffer.length >= 2) {
            const p0 = this.positionBuffer[0];
            const p1 = this.positionBuffer[1];
            const t = (now - p0.timestamp) / (p1.timestamp - p0.timestamp);

            // 插值计算位置
            const newPosition = new Vec3();
            Vec3.lerp(newPosition, p0.position, p1.position, t);
            
            // 更新位置
            this.node.setPosition(newPosition);
        }
    }

    onDestroy() {
        NetworkManager.instance.off('playerMove', this.onPlayerMove.bind(this));
        NetworkManager.instance.off('playerAttack', this.onPlayerAttack.bind(this));
        NetworkManager.instance.off('playerEvolve', this.onPlayerEvolve.bind(this));
    }
} 